layui.define(['baseUtil'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        upload = layui.upload,
        baseUtil = layui.baseUtil;

    var fileUtil = {
        /**
         * 删除文件
         */
        deleteFile: function (params, fn) {
            baseUtil.doPostData('/system/file/delete.do', params, function (data) {
                if (fn) fn(data);
            });
        },
        /**
         * 查询文件
         */
        selectFile: function (params, fn) {
            baseUtil.doPostData('/system/file/findList.do', params, function (data) {
                if (fn) fn(data);
            });
        },
        /**
         * 预览单图片
         */
        previewImage: function (id, name, src) {
            layer.photos({ photos: { title: '', id: '', start: 0, data: [{ pid: id, alt: name, src: src, thumb: src }] }, anim: 0 });
        },
        /**
         * 预览多图片
         */
        previewImages: function (elem) {
            var obj = $('#' + elem).parent();
            if (obj.find('img').length === 0) {
                return false;
            }
            var image;
            if (obj.find('img:last')[0].hasAttribute('src')) {
                image = obj.find('img');
            } else {
                image = obj.find('img:not(:last)');
            }
            image.unbind('click');
            image.bind('click', function () {
                var start = $(this).index();
                var photo = [];
                image.each(function (i, e) {
                    photo.push({ pid: e.id, alt: e.name, src: e.src, thumb: e.src });
                });
                layer.photos({ photos: { title: '', id: '', start: start, data: photo }, anim: 0 });
            });
        },
        /**
         * 显示图片
         */
        showImage: function (obj, objectId, width, height) {
            width = isBlank(width) ? 120 : width;
            height = isBlank(height) ? 120 : height;

            if (isNotBlank(objectId)) {
                fileUtil.selectFile({ objectId: objectId }, function (data) {
                    var str = '';
                    if (data != null && data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            str += '<img class="layui-upload-img" id="' + data[i].id + '" name="' + data[i].fileName + '" src=' + data[i].filePath + '"/system/file/showFile.do?filePath=" width="' + width + 'px" height="' + height + 'px">';
                        }
                    }
                    $('#' + obj).prepend(str);
                    fileUtil.previewImages(obj);
                });
            }
        },
        /**
         * 单图片上传
         */
        uploadImage: function (obj, objectId, fn, width, height) {
            //初始化参数
            width = isBlank(width) ? 120 : width;
            height = isBlank(height) ? 120 : height;
            objectId = isBlank(objectId) ? '' : objectId;
            //初始化界面
            $('#' + obj).prepend('<img class="layui-upload-img" name="' + obj + '" width="' + width + 'px" height="' + height + 'px"><input type="hidden" name="' + obj + '" value="' + objectId + '">');
            var image = $('img[name=' + obj + ']');
            var input = $('input[name=' + obj + ']');
            //初始化图片
            if (isNotBlank(objectId)) {
                fileUtil.selectFile({ objectId: objectId }, function (data) {
                    if (data != null) {
                        image.attr('src', '/system/file/showFile.do?filePath=' + data[0].filePath);
                    }
                });
            }
            //初始化监听
            var index;
            upload.render({
                elem: image,
                accept: 'images',
                url: '/system/file/uploadFile.do',
                headers: { token: getAccessToken() },
                before: function () {
                    index = layer.load(2);
                },
                done: function (result) {
                    layer.close(index);
                    if (result.code === 0) {
                        image.attr('src', '/system/file/showFile.do?filePath=' + result.data.filePath);
                        if (isNotBlank(objectId)) {
                            fileUtil.deleteFile({ objectId: objectId });
                        }
                        objectId = result.data.objectId;
                        input.val(result.data.objectId);
                        if (fn) fn(result.data);
                    } else if (result.code === 1) {
                        layer.msg(result.msg);
                    } else if (result.code === 2) {
                        requireLogin();
                    }
                }
            });
        },
        /**
         * 多图片上传
         */
        uploadImages: function (obj, objectId, width, height) {
            //初始化参数
            width = isBlank(width) ? 120 : width;
            height = isBlank(height) ? 120 : height;
            objectId = isBlank(objectId) ? '' : objectId;
            //初始化界面
            $('#' + obj).append('<img class="layui-upload-img" name="' + obj + '" width="' + width + 'px" height="' + height + 'px"><input type="hidden" name="' + obj + '" value="' + objectId + '">');
            var image = $('img[name=' + obj + ']');
            var input = $('input[name=' + obj + ']');
            //初始化图片
            fileUtil.showImage(obj, objectId, width, height);
            //初始化监听
            var index;
            var uploadInst = upload.render({
                elem: image,
                multiple: true,
                accept: 'images',
                url: '/system/file/uploadFile.do',
                data: { objectId: input.val() },
                headers: { token: getAccessToken() },
                before: function () {
                    index = layer.load(2);
                },
                done: function (result) {
                    if (result.code === 0) {
                        if (input.val() !== result.data.objectId) {
                            input.val(result.data.objectId);
                            uploadInst.reload({
                                data: { objectId: input.val() }
                            });
                        }
                        image.before('<img class="layui-upload-img" id="' + result.data.id + '" name="' + result.data.fileName + '" src=' + result.data.filePath + '"/system/file/showFile.do?filePath=" width="' + width + 'px" height="' + height + 'px">');
                        fileUtil.previewImages(obj);
                    } else if (result.code === 1) {
                        layer.msg(result.msg);
                    } else if (result.code === 2) {
                        requireLogin();
                    }
                },
                allDone: function () {
                    layer.close(index);
                }
            });
        },
        /**
         * 单文件上传
         */
        uploadFile: function (id, objectId, fn) {
            //初始化界面
            var str = '';
            str += '<input type="hidden" name="' + id + '" value="">';
            str += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="' + id + 'Btn">添加附件</button>';
            str += '<div class="layui-upload-list">';
            str += '<table class="layui-table">';
            str += '<tbody id="fileList"></tbody>';
            str += '</table>';
            str += '</div>';
            $('#' + id).html(str);
            //初始化文件
            if (isNotBlank(objectId)) {
                fileUtil.selectFile({ objectId: objectId }, function (data) {
                    fileUtil.showFile(data, false);
                });
            }
            //初始化监听
            var index;
            upload.render({
                elem: '#' + id + 'Btn',
                accept: 'file',
                url: '/system/file/uploadFile.do',
                headers: { token: getAccessToken() },
                before: function () {
                    index = layer.load(2);
                },
                done: function (result) {
                    layer.close(index);
                    if (result.code === 0) {
                        fileUtil.showFile([result.data], false);
                        if (isNotBlank(objectId)) {
                            fileUtil.deleteFile({ objectId: objectId });
                        }
                        objectId = result.data.objectId;
                        $('input[name="' + id + '"]').val(result.data.objectId);
                        if (fn) fn(result.data);
                    } else if (result.code === 1) {
                        layer.msg(result.msg);
                    } else if (result.code === 2) {
                        requireLogin();
                    }
                }
            });
        },
        /**
         * 多文件上传
         */
        uploadFiles: function (id, objectId, fn) {
            //初始化界面
            var str = '';
            str += '<input type="hidden" name="' + id + '" value="">';
            str += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="' + id + 'Btn">添加附件</button>';
            str += '<div class="layui-upload-list">';
            str += '<table class="layui-table">';
            str += '<tbody id="fileList"></tbody>';
            str += '</table>';
            str += '</div>';
            $('#' + id).html(str);
            //初始化文件
            if (isNotBlank(objectId)) {
                fileUtil.selectFile({ objectId: objectId }, function (data) {
                    fileUtil.showFile(data, true);
                });
            }
            //初始化监听
            var index;
            upload.render({
                elem: '#' + id + 'Btn',
                accept: 'file',
                url: '/system/file/uploadFile.do',
                headers: { token: getAccessToken() },
                data: { objectId: isBlank(objectId) ? '' : objectId },
                before: function () {
                    index = layer.load(2);
                },
                done: function (result) {
                    layer.close(index);
                    if (result.code === 0) {
                        fileUtil.showFile([result.data], true);
                        if (isBlank(objectId)) {
                            objectId = result.data.objectId;
                            $('input[name="' + id + '"]').val(result.data.objectId);
                        }
                        if (fn) fn(result.data);
                    } else if (result.code === 1) {
                        layer.msg(result.msg);
                    } else if (result.code === 2) {
                        requireLogin();
                    }
                }
            });
        },
        /**
         * 文件展示（可编辑）
         */
        showFile: function (data, append) {
            if (isNotEmpty(data)) {
                var str = '';
                data.forEach(function (e) {
                    str += '<tr>';
                    str += '<td class="layui-elip" style="width: 300px">';
                    str += '<i class="layui-icon layui-icon-link" style="font-size: 14px;margin-right: 5px"></i>' + e.fileName;
                    str += '</td>';
                    str += '<td><button class="layui-btn layui-btn-xs layui-btn-danger file-delete" id="' + e.id + '">删除</button></td>';
                    str += '</tr>';
                });
                var fileList = $('#fileList');
                if (append) {
                    fileList.append(str);
                } else {
                    fileList.html(str);
                }
                fileList.find('.file-delete').on('click', function () {
                    var tr = this.parentNode.parentNode;
                    fileUtil.deleteFile({ id: this.id }, function () {
                        $(tr).remove();
                    });
                    return false;
                });
            }
        },
        /**
         * 文件展示（不可编辑）
         */
        uploadFileShow: function (id, objectId) {
            //初始化界面
            var str = '';
            str += '<div class="layui-upload-list">';
            str += '<table class="layui-table">';
            str += '<tbody id="fileList"></tbody>';
            str += '</table>';
            str += '</div>';
            $('#' + id).html(str);
            //初始化文件
            if (isNotBlank(objectId)) {
                fileUtil.selectFile({ objectId: objectId }, function (data) {
                    if (isNotEmpty(data)) {
                        var str = '';
                        data.forEach(function (e) {
                            str += '<tr>';
                            str += '<td class="layui-elip" style="width: 300px">';
                            str += '<i class="layui-icon layui-icon-link" style="font-size: 14px;margin-right: 5px"></i>' + e.fileName;
                            str += '</td>';
                            str += '<td><button class="layui-btn layui-btn-xs layui-btn-danger file-download" id="' + e.id + '">下载</button></td>';
                            str += '</tr>';
                        });
                        $('#fileList').html(str).find('.file-download').on('click', function () {
                            document.location.href = '/system/file/downloadFile.do?id=' + this.id;
                            return false;
                        });
                    }
                });
            }
        }
    };
    exports('fileUtil', fileUtil);
});
